package com.chao.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/17
 */
public class ConditionAwait {

    public static void main(String[] args) {

        Resource3 resource3 = new Resource3();
        new Thread(() ->{
            for (int i = 0; i < 5; i++) {
                resource3.printA();
            }
        },"A").start();

        new Thread(() ->{
            for (int i = 0; i < 5; i++) {
                resource3.printB();
            }
        },"B").start();

        new Thread(() ->{
            for (int i = 0; i < 5; i++) {
                resource3.printC();
            }
        },"C").start();
    }
}

class Resource3{

    private int num = 1;

    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            while (num != 1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "==> AAA");
            num = 2;
            condition2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            while (num != 2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "==> BBB");
            num = 3;
            condition3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            while (num != 3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "==> CCC");
            num = 1;
            condition1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
